'Copyright (C) 2009 Christiaan Cable
'
'This program is free software; you can redistribute it and/or
'modify it under the terms of the GNU General Public License
'as published by the Free Software Foundation; either version 3
'of the License, or (at your option) any later version.
'
'This program is distributed in the hope that it will be useful,
'but WITHOUT ANY WARRANTY; without even the implied warranty of
'MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
'GNU General Public License for more details (LICENCE.TXT).

Imports System.Windows.Forms

Public Class Primus
    Public ISPReturnData As New ISPReturnData
    Private CookieContainer As New System.Net.CookieContainer

    Public Sub New(ByVal ConfigurationData As ConfigurationData)

        Try
            'set rollover date
            SetRolloverDate(ConfigurationData, ISPReturnData)

            Dim strHTMLData As String

            'get login cookie
            ISPGet("https://toolbox.iprimus.com.au/formslogin.asp", CookieContainer, System.Net.CredentialCache.DefaultCredentials)

            Dim NewTimeSpan As TimeSpan = TimeSpan.FromMilliseconds(CType(NewTimeSpan.Milliseconds, Double))
            Dim NewDateTime As DateTime = New DateTime(1900, 1, 1)
            NewDateTime += NewTimeSpan
            Dim TimeZoneOffset As String = CInt(TimeZone.CurrentTimeZone.GetUtcOffset(NewDateTime).TotalMinutes - 60).ToString

            'login
            Dim POSTData As String = "Username=" & ConfigurationData.Username & "&password=" & ConfigurationData.Password & "&submit=Login&URL=&timezoneoffset=-" & TimeZoneOffset

            Dim strTemp As String = ISPPost("https://toolbox.iprimus.com.au/verifpwd.asp", POSTData, CookieContainer, System.Net.CredentialCache.DefaultCredentials)

            'process response
            If strTemp.Contains("<H3>Login</H3>") = True Then
                ISPReturnData.ErrorMessage = "Login Failed"
                Exit Sub
            End If

            'get usage
            strHTMLData = ISPGet("https://toolbox.iprimus.com.au/UsageOverall.asp", CookieContainer, System.Net.CredentialCache.DefaultCredentials)

            If UA.DebugISP = True Then My.Computer.FileSystem.WriteAllText(GetAppDataPath() & "debug.htm", strHTMLData, False, System.Text.Encoding.ASCII)

            'logout
            ISPGet("https://toolbox.iprimus.com.au/logout.asp", CookieContainer, System.Net.CredentialCache.DefaultCredentials)

            'strHTMLData = My.Computer.FileSystem.ReadAllText("C:\programming\isp\primus\UsageOverall.asp.html", System.Text.Encoding.ASCII)

            'process response
            If strHTMLData <> "" Then

                'determine start of usage data
                'Period from
                Dim Offset As Integer = 1
                Dim Start As Integer = 0
                Dim Finish As Integer = 0
                Dim StartDate As Date
                Dim EndDate As Date
                Dim Found As Boolean = False

                Do While InStr(Offset, strHTMLData, "Period from") > 0
                    Start = InStr(Offset, strHTMLData, "Period from")
                    Finish = InStr(Start, strHTMLData, "/b>")

                    strTemp = Mid(strHTMLData, Start, Finish - Start)

                    'get dates
                    StartDate = CDate(ExtractText(strTemp, ", ", 0, "", " to "))
                    EndDate = CDate(ExtractText(strTemp, " to ", 0, ", ", "<"))

                    'check range
                    If StartDate < Now And EndDate.AddDays(1) > Now Then
                        'get values
                        Finish = InStr(Start, strHTMLData, "<input name=")
                        strTemp = Mid(strHTMLData, Start, Finish - Start)

                        ISPReturnData.PeakUpload = CSng(Val(ExtractText(strTemp, "m&nbsp;</td>", 0, ">", " ")))
                        ISPReturnData.PeakDownload = CSng(Val(ExtractText(strTemp, "m&nbsp;</td><td class=""clsTableBody"">", 0, "Body"">", " ")))

                        '##########################################################

                        'create graph data
                        'peak
                        ISPReturnData.GraphItemList.Add(New GraphItem("Peak " & Format(System.Math.Floor((ISPReturnData.PeakDownload / Val(ConfigurationData.PeakUsageLimit)) * 1000) / 10, "#0.0") & "% (" & ISPReturnData.PeakDownload & " MB)", ISPReturnData.PeakDownload, CSng(Val(ConfigurationData.PeakUsageLimit)), ISPReturnData.PeakNow))

                        'days elapsed
                        ISPReturnData.GraphItemList.Add(New GraphItem("Days Elapsed " & Format((ISPReturnData.DaysUsed / (ISPReturnData.DaysUsed + ISPReturnData.DaysLeft)) * 100, "#0") & "% (" & ISPReturnData.DaysUsed & " Days)", ISPReturnData.DaysUsed, ISPReturnData.DaysUsed + ISPReturnData.DaysLeft, False))

                        '##########################################################

                        'create stats data
                        ISPReturnData.TextItemList.Add(New TextItem("Usage Left :", ISPReturnData.PeakUsageRemainingDescription))
                        ISPReturnData.TextItemList.Add(New TextItem("Usage Avg. Left :", ISPReturnData.PeakUsageRemainingPerDayDescription))

                        ISPReturnData.TextItemList.Add(New TextItem("Downloads :", ISPReturnData.PeakDownload & " MB"))
                        ISPReturnData.TextItemList.Add(New TextItem("Uploads :", ISPReturnData.PeakUpload & " MB"))

                        If ISPReturnData.ShapedNow = False Then
                            ISPReturnData.TextItemList.Add(New TextItem("Shaped :", "NO"))
                        Else
                            ISPReturnData.TextItemList.Add(New TextItem("Shaped :", "YES"))
                        End If

                        '##########################################################

                        'process alerts
                        ProcessAlerts(ConfigurationData, ISPReturnData)

                        Exit Sub
                    End If
                    Offset = Finish
                Loop

                ISPReturnData.ErrorMessage = "Error Parsing Website"
            End If
        Catch ex As Exception
            ISPReturnData.ErrorMessage = ex.Message
        End Try

    End Sub
End Class
